<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>鼠标拖拽</title>
    <style>
      .box {
        position: relative;
      }
      .div {
        width: 200px;
        height: 100px;
        background-color: orange;
        box-shadow: 0 0 10px;
        position: absolute;
        cursor: move;
        text-align: center;
        line-height: 100px;
        user-select: none;
      }
    </style>
  </head>
  <body>
    <div class="box"><div class="div">按下移动鼠标</div></div>
  </body>
  <script>
    // 拖动的主要目的：将鼠标移动的距离同步到指定的标签上
    var div = document.querySelector(".div");

    div.addEventListener("mousedown", function (e) {
      // 记录鼠标按下时鼠标初始位置
      var startX = e.pageX;
      var startY = e.pageY;
      // 记录鼠标按下时元素初始位置
      var left = div.offsetLeft;
      var top = div.offsetTop;

      function mouse(e) {
        // 鼠标移动时，实时记录偏移量
        let offsetX = e.pageX - startX;
        let offsetY = e.pageY - startY;
        // 同步到想要拖动的元素上
        div.style.left = left + offsetX + "px";
        div.style.top = top + offsetY + "px";
      }

      function up() {
        // 鼠标松开时删除副作用事件
        document.removeEventListener("mouseup", up);
        document.removeEventListener("mousemove", mouse);
      }

      // 添加 mousemove/mouseup 事件
      document.addEventListener("mousemove", mouse);
      document.addEventListener("mouseup", up);
    });
  </script>
</html>
